/*
 * Copyright (c) 2024 Black Sesame Technologies
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "dal_fastdds/entity_impl/DalDataWriterImpl.hpp"
#ifdef DAL_ENABLE_DMABUFHEAP
#include "dal_builtin/msg/dal_dma_buf_heap_send_notify_msg.hpp"
#endif

DalDataWriterImpl::DalDataWriterImpl(DataWriter* fastdds_datawriter,
                                     DataWriterListenerImpl* listener)
{
    fastdds_datawriter_ = fastdds_datawriter;
    listener_ = listener;
}

DalDataWriterImpl::~DalDataWriterImpl()
{
#ifdef DAL_ENABLE_DMABUFHEAP
    if (dbh_writer_)
        delete dbh_writer_;
#endif
}

DataWriter*& DalDataWriterImpl::FastddsDataWriter()
{
    return fastdds_datawriter_;
}

void DalDataWriterImpl::SetFastddsDataWriter(DataWriter* fastdds_datawriter)
{
    fastdds_datawriter_ = fastdds_datawriter;
}

Publisher*& DalDataWriterImpl::FastddsPublisher()
{
    return fastdds_pub_;
}

void DalDataWriterImpl::SetFastddsPublisher(Publisher*& publisher)
{
    fastdds_pub_ = publisher;
}

DomainParticipant*& DalDataWriterImpl::FastddsDomainParticipant()
{
    return fastdds_participant_;
}

void DalDataWriterImpl::SetFastddsDomainParticipant(DomainParticipant*& participant)
{
    fastdds_participant_ = participant;
}

void DalDataWriterImpl::SetTypeSupport(const void* type_support)
{
    type_support_ = type_support;
}

ReturnCode_t DalDataWriterImpl::DDSWrite(void* data, const InstanceHandle_t& instance_handle)
{
    dal_fastrtps_shared_cpp::SerializedData sdata;
    sdata.is_cdr_buffer = false;
    sdata.data = static_cast<void*>(data);
    sdata.impl = type_support_;

    return fastdds_datawriter_->write(&sdata, instance_handle);
}

#ifdef DAL_ENABLE_DMABUFHEAP
ReturnCode_t DalDataWriterImpl::DBHWrite(void* data, const InstanceHandle_t& instance_handle)
{
    if (!dbh_writer_ || !dbh_writer_->Write(data))
        return ReturnCode_t::RETCODE_ERROR;
    
    return ReturnCode_t::RETCODE_OK;
}
#endif
